﻿using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using RestSharp;
using Spotted.Core;
using Spotted.Core.ExtensionMethods;
using Spotted.Data.Entities;

namespace Spotted.Data.Repositories.Impl
{
    public class RestGooglePlacesRepository : IPlacesRepository
    {
        private const string GoogleApiKey = "AIzaSyC96EM60SwCSUiqV3sV7D0sQkj5BZbLbW4";
        private IList<Place> _placesList;
 
        public RestGooglePlacesRepository()
        {
            _placesList = new List<Place>();
        }

        #region Implementation of IPlacesRepository

        /// <summary>
        /// A list of the places found near the given point
        /// </summary>
        public IList<Place> Places
        {
            get { return _placesList; }
        }

        public void FindNearbyPlaces(double latitude, double longitude)
        {
            var client = new RestClient("https://maps.googleapis.com/maps/api");
            var request = new RestRequest("place/search/json", Method.GET);
            request.AddParameter("key", GoogleApiKey);
            request.AddParameter("location", string.Format("{0},{1}", latitude, longitude));
            request.AddParameter("sensor", "true");
            request.AddParameter("radius", 30);

            client.ExecuteAsync(request, (response, handler) =>
            {
                JObject jsonObject = JObject.Parse(response.Content);
                JArray resultsArray = JArray.Parse(jsonObject["results"].ToString());

                var locationList = (from a in resultsArray
                                    select new Place
                                    {
                                        ID = a["id"].ToString(),
                                        Name = a["name"].ToString(),
                                        Rating = a["rating"] == null ? double.NaN : a["rating"].ToString().AsDouble(),
                                        Types = (from t in JArray.Parse(a["types"].ToString())
                                                 select t.ToString()).ToList(),
                                        Latitude = a["geometry"]["location"]["lat"].ToString().AsDouble(),
                                        Longitude = a["geometry"]["location"]["lng"].ToString().AsDouble()
                                    }).ToList();

                _placesList = locationList.Where(l => !l.Types.Contains(Constants.GOOGLE_PLACES_ROUTE_TEXT) &&
                    !l.Types.Contains(Constants.GOOGLE_PLACES_NEIGHBORHOOD_TEXT)).ToList();

                if (FindNearbyPlacesCompleted != null)
                    FindNearbyPlacesCompleted(this, new EventArgs());
            });
        }

        public event EventHandler FindNearbyPlacesCompleted;

        #endregion
    }
}
